/**
 * 首页质控的批处理 页面
 */

	//显示遮罩层div
	function showBgDiv_Quality(){
		$('#'+tabId+' #shade').fadeIn();
		//设置对象的模糊效果
		$('#'+tabId+' #con').css('-webkit-filter','blur(8px)');

	}

	//关闭遮罩层div，并清空显示数据
	function closeBgDiv_Quality(){
		//初始化遮罩层内容
		$('#'+tabId+' #shade').fadeOut();
		//取消对象的模糊效果
		$('#'+tabId+' #con').css('-webkit-filter','');
		
		$('#'+tabId+' #progress_info_total').html('');
		$('#'+tabId+' #progress_info_detail').html('');
		
		$('#'+tabId+' .progress-bar').css('width','0%');
		$('#'+tabId+' .progress-bar span').html('');
		$('#'+tabId+' #close_loading_btn').fadeOut();//隐藏关闭按钮
	
	}

$(function(){
	var form = $("#mrQualityExecuteForm");
	var progressBar ;//页面进度条
	var setIntervalId;//进度条定时器
	var timerId; //计时器的 定时器
	//时间类型下拉框内容
	var dataTypeContents  = [{title: "出院日期", value: "outDate", selected: true},//默认值
	                         {title: "推送日期", value: "pushDate"}];
	//起始日期
	$("#"+tabId+" #dateFrom").val(drgsDate.dateFrom);	
	$("#"+tabId+" #dateFrom").datetimepicker({
		format : "yyyy-mm-dd", //yyyy-mm-dd hh:ii:ss
		autoclose : true,//当选择一个日期之后是否立即关闭此日期时间选择器
		todayBtn : true,//在日期时间选择器组件的底部显示一个 “Today” 按钮用以选择当前日期.如果是true的话，”Today” 按钮仅仅将视图转到当天的日期，如果是”linked”，当天日期将会被选中
		minView : 2,  //日期时间选择器所能够提供的最精确的时间选择视图  0:分钟，1:小时，2:天，3:月，4:年
		language : 'zh-CN'
	});
	//结束日期
	$("#"+tabId+" #dateTo").val(drgsDate.dateTo);
	$("#"+tabId+" #dateTo").datetimepicker({
		format : "yyyy-mm-dd",
		autoclose : true,
		todayBtn : true,
		minView : 2,
		language : 'zh-CN'
	});
	//批处理数量
	$("#"+tabId+" #batchSize").val(5000);
	//初始化时间类型选择框
	form.find('#dateType_').select({
       title: '请选择',
       contents: dataTypeContents
    }).on('change',function(){
       form.find('#dateType').val($(this).getValue());
    });
	$.each(dataTypeContents,function(i,data){
		if(data.selected){
			$("#dateType").val( data.value );
		}
	});
	//开始批处理
	$("#"+tabId+" #executeStart").on('click', function(){  
		var dateFrom = $("#"+tabId+" #dateFrom").val();
		var dateTo = $("#"+tabId+" #dateTo").val();
		/**
		 * 日期验证
		 */
		//校验是否填写
		if(dateFrom =='' || dateTo ==''){
			drgUI.warning("请选择日期") ;
			return;
		}
		//比较大小
		if(new Date(dateFrom)>new Date(dateTo)){
			drgUI.error("开始日期不能大于结束日期") ;
			return;
		};
		//校验批处理数量
		var batchSize = $("#batchSize").val();
        var reg = new RegExp(/^[0-9]*$/);
        if (!reg.test(batchSize) || batchSize < 1 ) {
			drgUI.error("批处理数量为大于0的整数") ;
			return;
        }
        //校验日期类型
		var dateType = $("#dateType").val();
        if (!dateType) {
			drgUI.error("请选择日期类型") ;
			return;
        }
        //ajax加载动画 '0':去掉 ， '1':添加
        drgUI.bindAjaxStart('0');//去掉ajax加载动画
        //
		drgUI.confirm({
			content : '确定开始质控吗？',
			callSure : function() {
				$("#"+tabId+" #executeStart").attr({"disabled":"disabled"});//按钮为禁用
				var totalCount = 0;//病例总数
				var clearTimerFlag = false;//是否已经清除定时器
				var symbolCount = 0 ;
				//开始质控
				$.ajax({
					url:contextPath+"/medicalRecordQuality/startBatchAnalysis.dhc",
					type:"post",
					data:{dateFrom: dateFrom, dateTo: dateTo,dateType: dateType,batchSize: batchSize},
					success:function(result){

					//数据加载成功
						//所选时间范围内有病例数据
						if(totalCount > 0){
                            var progressInfo = result.data
							//加载提示信息 
							$('#'+tabId+' #progress_info_total').html(totalCount);
							$('#'+tabId+' #progress_info_count').html('已经处理：'+totalCount);
							//将进度条设为100%
							$('#'+tabId+' .progress-bar').css('width','100%');
							$('#'+tabId+' .progress-bar span').html('100%');						
						}else{
							drgUI.warning("选择的日期范围内没有数据") ;						
						}						
						//清除进度条定时器
						clearInterval(setIntervalId);
						//如果计时器还没有被清除，则清除计时器的定时器
						if( !clearTimerFlag ){
							clearInterval(timerId);
						}					
						//将分组按钮可用
						$("#"+tabId+" #executeStart").removeAttr("disabled");
						//关闭遮罩层div，并清空显示数据
//						closeBgDiv_Quality();
						//显示关闭按钮
						$('#'+tabId+' #close_loading_btn').fadeIn();
					},
					error:function(result){
						drgUI.error("请求失败") ;
						//清除计时器的定时器
						clearInterval(timerId);
						//显示关闭按钮
						$('#'+tabId+' #close_loading_btn').fadeIn();
						//将分组按钮可用
						$("#"+tabId+" #executeStart").removeAttr("disabled");
						var progressInfo = result.data
						//病例总数
						totalCount = parseInt(progressInfo.totalCount) ;
						var nowCount = 0;//当前已处理数据条数
						//当前第几批（从1开始）
						var batchNowNum = 1;
						var detailContent = '' ;
						var message = "" ;
						if(totalCount){
							$('#'+tabId+' #progress_info_div').fadeIn();
							batchNowNum = parseInt(progressInfo.batch);
							var pageSize = parseInt(batchSize);
							//当前批次中的 已处理数据条数
							nowCount = parseInt(progressInfo.nowCount) ;
							var nowPercent = GetPercent(nowCount, totalCount);
							//总共分几批
							var batchNum = parseInt(progressInfo.batchNum);
							detailContent = '计划分&nbsp;&nbsp;'+batchNum+'&nbsp;&nbsp;批处理，当前批次：';								
							var hightNum = 0;
							//如果有错误提示信息则一起显示
							for(var i=1;i<batchNum;i+=1){
								if(progressInfo["errmsg"+i]){
									detailContent += progressInfo["errmsg"+i]+'<br/>';
									hightNum++;
								}
							}
							//修改提示信息容器的高度
							if(hightNum){
								hightNum = hightNum * 22 ; 					
								var shadeHight = parseInt($("#shade").height());
								shadeHight = shadeHight + hightNum ;
								$("#shade").height(shadeHight+'px');
								
								var shadeDivHight = parseInt($("#shade_div").height());
								shadeDivHight = shadeDivHight + hightNum ;
								$("#shade_div").height(shadeDivHight+'px');
							}							
						}else{
							$('#'+tabId+' #progress_info_div').fadeOut();
							totalCount = 0 ;
							nowCount = 0 ;
							nowPercent = '0%';
							detailContent = progressInfo.desc ;
                            message = progressInfo.message ;
						}
						//加载提示信息 
						$('#'+tabId+' #progress_info_total').html(totalCount);
						$('#'+tabId+' #progress_info_count').html('已经处理：'+nowCount);
						$('#'+tabId+' #progress_info_batch').html(detailContent);
						$('#'+tabId+' #progress_info_batch_num').html(batchNowNum);
						//加载进度条 
						$('#'+tabId+' .progress-bar').css('width',nowPercent);
						$('#'+tabId+' .progress-bar span').html(nowPercent);
					}
				});

				//清空显示数据
				closeBgDiv_Quality();
				//显示进度条
				showBgDiv_Quality();
				//启动计时器
				timerStart(100,'myClock');
				//启动进度条定时器
				var setIntervalId  = setInterval(function(){
					$.ajax({
						url:contextPath+"/medicalRecordQuality/getBatchAnalysisParameter.dhc",
						type:"post",
						data:{},
					    dataType:"json",
					    async:false,//同步
						success:function(result){
							var progressInfo = result.data;
							//病例总数
							totalCount = parseInt(progressInfo.totalCount) ;
							var nowCount = 0;//当前已处理数据条数
							//当前第几批（从1开始）
							var batchNowNum = 1;
							var detailContent = '' ;
							var countContent = '';
							// 进度信息
                            var scheduleMessage = "" ;
							if(totalCount){
								$('#'+tabId+' #progress_info_div').fadeIn();
								batchNowNum = parseInt(progressInfo.batch);
								var pageSize = parseInt(batchSize);
								//当前批次中的 已处理数据条数
								nowCount = parseInt(progressInfo.nowCount) ;
                                countContent = '已处理 &nbsp;&nbsp;'+nowCount+' &nbsp;&nbsp;条';
                                scheduleMessage = progressInfo.message ;
								// if(nowCount){
								// 	countContent = '已处理 &nbsp;&nbsp;'+nowCount+' &nbsp;&nbsp;条';
								// }else{
								// 	if( symbolCount % 4 == 0 ){
								// 		countContent = '正在查询数据  ';
								// 	}else if( symbolCount % 4 == 1 ){
								// 		countContent = '正在查询数据  。';
								// 	}else if( symbolCount % 4 == 2 ){
								// 		countContent = '正在查询数据  。。';
								// 	}else if( symbolCount % 4 == 3 ){
								// 		countContent = '正在查询数据  。。。';
								// 	}else{
								// 		countContent = '正在查询数据';
								// 	}
								// 	symbolCount++;
								// }
                                // scheduleMessage
                                var nowPercent = GetPercent(nowCount, totalCount);
								//总共分几批
								var batchNum = parseInt(progressInfo.batchNum);
								detailContent = '计划分&nbsp;&nbsp;'+batchNum+'&nbsp;&nbsp;批处理，当前批次：';								
								var hightNum = 0;
								//如果有错误提示信息则一起显示
								for(var i=1;i<batchNum;i+=1){
									if(progressInfo["errmsg"+i]){
										detailContent += progressInfo["errmsg"+i]+'<br/>';
										hightNum++;
									}
								}
								//修改提示信息容器的高度
								if(hightNum){
									hightNum = hightNum * 22 ; 					
									var shadeHight = parseInt($("#shade").height());
									shadeHight = shadeHight + hightNum ;
									$("#shade").height(shadeHight+'px');
									
									var shadeDivHight = parseInt($("#shade_div").height());
									shadeDivHight = shadeDivHight + hightNum ;
									$("#shade_div").height(shadeDivHight+'px');
								}
								if(totalCount == nowCount){
									//清除计时器的定时器
									clearInterval(timerId);
									clearTimerFlag = true;
								}
							}else{
								$('#'+tabId+' #progress_info_div').fadeOut();
								totalCount = 0 ;
								if( symbolCount % 4 == 0 ){
									countContent = '正在查询数据  ';
								}else if( symbolCount % 4 == 1 ){
									countContent = '正在查询数据  。';
								}else if( symbolCount % 4 == 2 ){
									countContent = '正在查询数据  。。';
								}else if( symbolCount % 4 == 3 ){
									countContent = '正在查询数据  。。。';
								}else{
									countContent = '正在查询数据';
								}
								symbolCount++;
								nowPercent = '0%';
								detailContent = progressInfo.desc ;
							}
							//加载提示信息 
							$('#'+tabId+' #progress_info_total').html(totalCount);
							$('#'+tabId+' #progress_info_count').html(countContent);
							$('#'+tabId+' #progress_info_batch').html(detailContent);
							$('#'+tabId+' #progress_info_batch_num').html(batchNowNum);
                            $('#'+tabId+' #progress_info_message').html(scheduleMessage);
							//加载进度条 
							$('#'+tabId+' .progress-bar').css('width',nowPercent);
							$('#'+tabId+' .progress-bar span').html(nowPercent);							
						}
					});

				}, 600);
			/////////
			}//end callSure function
		});
		return false;
	});  

	//计算两个整数的百分比值,最大值为100%
	function GetPercent(num, total) { 
		num = parseFloat(num); 
		total = parseFloat(total); 
		if (isNaN(num) || isNaN(total)) { 
			return "0%"; 
		}
		var myPercent = Math.round(num / total * 10000) / 100.00;
		return total <= 0 ? "0%" : (myPercent>100.00 ? 100.00:myPercent + "%"); 
	}	
	
	//计时器  defineTime为间隔毫秒数，最好是100的整数倍，不能为0
	function timerStart(defineTime,clockId){
        var h = 0,m = 0,s = 0,t = 0,ms = 0;
        var time = parseInt(defineTime);
        if(time){
        	timerId = setInterval(function(){
                t = t + time ;
                s = s + Math.floor(t/1000);
                t = t - Math.floor(t/1000) * 1000 ;
                ms = Math.round((t % 1000)/100);
 
				if (s==60) {
					s=0;
					m++;
				}
				if (m==60) {
					m=0;
					h++;
				}
				$('#'+tabId+' #'+clockId).html((h>9?h:('0'+h))+':'+(m>9?m:('0'+m))+':'+(s>9?s:('0'+s))+'.'+ms);
			}, time)			
		}else{
			return false;
		}
	}
	
});
